#include <stdio.h>
#include <pthread.h>
/*
    线程互斥锁也是一个信号量,只不过线程互斥锁,存在于进程的地址空间,
    在用于线程间同步和互斥时,线程互斥锁效率要比信号量的效率要高
    int pthread_mutex_init(pthread_mutex_t * mutex,
               const pthread_mutexattr_t * attr):
        初始化一个线程互斥锁
        参数1：锁
        参数2：NULL
    int pthread_mutex_lock(pthread_mutex_t *mutex)：
        上锁P
    int pthread_mutex_unlock(pthread_mutex_t *mutex)：
        解锁V
    int pthread_mutex_destroy(pthread_mutex_t *mutex)：
        销毁一个互斥锁
*/
int data = 0;//共享

void* thread1(void* arg)
{
    pthread_detach(pthread_self());
    int i = 100000;
    while (i--)
    {
        pthread_mutex_lock((pthread_mutex_t*)arg);//P
        data++;
        printf("thread1 data:%d\n", data);
        pthread_mutex_unlock((pthread_mutex_t*)arg);//V
    }
}

void* thread2(void* arg)
{
    pthread_detach(pthread_self());
    int i = 100000;
    while (i--)
    {
        pthread_mutex_lock((pthread_mutex_t*)arg);//P
        data++;
        printf("thread2 data:%d\n", data);
        pthread_mutex_unlock((pthread_mutex_t*)arg);//V
    }
}

int main()
{
    //1.初始化互斥锁
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex, NULL);

    //2.创建两个线程
    pthread_t t1, t2;
    pthread_create(&t1, NULL, thread1, &mutex);
    pthread_create(&t2, NULL, thread2, &mutex);

    while (1);
    pthread_mutex_destroy(&mutex);

}